package com.gsk.IOCcontain;

import java.util.*;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLLoader {

    //1.获取document对象
    public static Document parse(String filename) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(XMLLoader.class.getClassLoader().getResource(filename)); // 读取XML文件,获得document对象
        return document;
    }

    //2.得到属性和依赖集合beanDefinitionList
    public static List<BeanDefinition> getBeansElement(Document document){
        //获取根结点，得到所有bean的整体内容
        Element root=document.getRootElement();
        List<Element> beanList = root.elements("bean");

        //目的是获取一个BeanDefinition集合，未解析的各个bean的具体内容
        return getBeanDefinitionList(beanList);
    }

    //具体如何得到xml中定义的属性和依赖
    public static List<BeanDefinition> getBeanDefinitionList(List<Element> beanList){

        List<BeanDefinition> beanDefinitionList=new ArrayList<>();

        //得到bean的id,class,property
        for(Element element:beanList){
            //BeanDefinition属性初始化
            String id=null;
            String className=null;
            Map<String,Map<String,String>> propertites=new HashMap<>();

            //1.获取所有attributes，并分别存入id,class中
            for(Attribute attribute:element.attributes()){
                if(attribute.getName().equals("id")){
                    id=attribute.getValue();
                }
                if(attribute.getName().equals("class")){
                    className=attribute.getValue();
                }
            }

            //2.获取所有属性注入property
            if(element.elements().size()!=0) {
                for (Element element1 : element.elements("property")) {

                    String name = null;
                    String state = null;
                    String value = null;

                    for (Attribute attribute : element1.attributes()) {
                        if (attribute.getName().equals("name")) {
                            name = attribute.getValue();
                        }
                        if (attribute.getName().equals("ref")) {
                            state = attribute.getName();
                            value = attribute.getValue();
                        }
                        if (attribute.getName().equals("value")) {
                            state = attribute.getName();
                            value = attribute.getValue();
                        }
                    }
                    Map<String, String> map = new HashMap<>();
                    map.put(state, value);
                    propertites.put(name, map);
                }
            }
            beanDefinitionList.add(new BeanDefinition(id,className,propertites));
        }

        return beanDefinitionList;
    }
}